package com.ktjy.temp.mqtt.controller;

import com.alibaba.fastjson.JSONArray;
import com.ktjy.temp.mqtt.config.emqx.EmqxApiClient;
import com.ktjy.temp.mqtt.service.DeviceDataService;
import com.ktjy.temp.mqtt.service.DeviceEmqxClientService;
import com.ktjy.temp.pojo.DeviceEmqxClient;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * mqtt服务器相关接口,业务暂时不需要
 */
@Controller
@RequestMapping("/emqxapi")
public class EmqxApiController {

    @Resource
    EmqxApiClient emqxApiClient;

    @Resource
    DeviceEmqxClientService deviceEmqxClientService;

    @Resource
    DeviceDataService deviceDataService;

    /**
     * 通过发送http请求获取设备在线状态
     * 获取所有在线客户端
     * 暂时业务不需要
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getDeviceInfo")
    public Object getDeviceInfo() {
        JSONArray onlineClients = null;
        try {
            onlineClients = emqxApiClient.getOnlineClients();
//            for (Object client : onlineClients) {
//                JSONObject c = (JSONObject) client;
//                EmqxClientInfo javaObject = c.toJavaObject(EmqxClientInfo.class);
//                System.out.println(javaObject);
//            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return onlineClients;
    }


    /**
     * 通过emqx提供的在线设备接口获取所有在线客户端,将实时设备信息添加到数据库中
     * 暂时业务不需要
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/add")
    public Object add() throws Exception {
        Integer count = 0;
        //通过emqx工具类获取目前的设备的信息
        JSONArray onlinCelients = emqxApiClient.getOnlineClients();
        for (int i = 0; i < onlinCelients.size(); i++) {
            DeviceEmqxClient javaObject = onlinCelients.getJSONObject(i).toJavaObject(DeviceEmqxClient.class);
            deviceEmqxClientService.add(javaObject);
            count++;
        }
        return count;
    }
}
